var $tab = $('#sql-tab-result');
var $nav = $tab.find('.am-tabs-nav');
var $bd = $tab.find('.am-tabs-bd');

var prefix = ctx + "osfw/dbadminer/database/sql";

// --------------------------------------------------------------------------------------------------------------------


/**
 * 相关封装
 */
(function ($) {
    $.extend({
        resultTab: {
            // 初始化执行结果信息页
            init: function (_clz) {
                if ($(".fw-sql-result").hasClass("am-hide")) {
                    $(".fw-sql-result").removeClass("am-hide");
                }
                $.resultTab.closeTab(_clz);
                $("#result-info p, #result-info hr").remove();
                $(".result-info").addClass("am-active");
            },
            // 添加执行sql结果选项卡
            addTab: function (_clz, _title, _index, _sql, _total, _time) {
                var nav =
                    '<li class="' + _clz + '" data-sql="' + _sql + '" data-total="' + _total + '" data-time="' + _time + '">' +
                    '   <a href="javascript: void(0)">' + _title + _index + '</a>' +
                    '</li>';
                var content =
                    '<div class="am-tab-panel ' + _clz + '">' +
                    '   <table id="' + _clz + '-' + _index + '" class="am-table am-table-bordered result-data-table"></table>' +
                    '</div>';
                $nav.append(nav);
                $bd.append(content);
                $tab.tabs('refresh');
            },
            // 绘制执行信息选项卡
            drawInfoTab: function (_clz, _title, data) {
                if ($("#result-info p").length == 0) {
                    $.each(data, function (index, item) {
                        setTimeout(function () {
                            if ($("#result-info").children("p").length > 0) {
                                $("#result-info").append(`<p><hr data-am-widget="divider" style="" class="am-divider am-divider-dashed" /></p>`);
                            }
                            $("#result-info").append(`<p>` + item.stmt + `</p>`);
                            $("#result-info").append(`<p>> ` + item.msg + `</p>`);
                            $("#result-info").append(`<p>> 时间：` + item.times + `s</p>`);

                            if (index == data.length - 1) {
                                $.resultTab.drawDataTab(_clz, _title, data);
                            }
                        }, 300 * index);
                    });
                } else {
                    $.resultTab.drawDataTab(_clz, _title, data);
                }
            },
            // 绘制表格数据选项卡
            drawDataTab: function (_clz, _title, data) {
                var _index = 0;
                $.each(data, function (index, item) {
                    if (item.data != null && item.code == 200 && item.type != "modify" && item.type != "other") {
                        _index += 1;
                        $.resultTab.addTab(_clz, _title, _index, item.stmt, item.total, item.times);
                        $.dataTable.drawTable(_clz + "-" + _index, item);
                    }
                });
                setTimeout(function () {
                    $(".result-data:first a").click();
                }, 300);
            },
            // 关闭选项卡
            closeTab: function (clz) {
                $("." + clz + "*").remove();
                $tab.tabs('refresh');
            },
        },
        // 数据表格封装处理
        dataTable: {
            // 执行sql并添加tab
            executeTab: function (_clz, _title) {
                $("#fw-toolbar-export").addClass("am-hide");
                // var form_obj = $("#form-sql-search").serializeObject();
                // var json_data = JSON.stringify(form_obj);
                var form_data = $("#form-sql-search").serialize();
                $.operate.post(prefix + "/execute", form_data, function (res) {
                    if (res.data != null) {
                        $.resultTab.drawInfoTab(_clz, _title, res.data);
                    }
                }, function (res) {
                    $.dataTable.executeTab(_clz, _title);
                });
            },
            // 执行sql更新表格体
            executeOne: function (sql_code, page, callback) {
                /*var form_obj = $("#form-sql-search").serializeObject();
                if (sql_code != undefined && sql_code != null) {
                    form_obj["sqlCode"] = sql_code;
                }
                if (page != undefined && page != null) {
                    form_obj["page"] = page;
                }
                var json_data = JSON.stringify(form_obj);*/
                var form_data = $("#form-sql-search").serializeArray();
                if (sql_code != undefined && sql_code != null) {
                    form_data.push({"sqlCode": sql_code});
                }
                if (page != undefined && page != null) {
                    form_data.push({"page": page});
                }
                $.operate.post(prefix + "/execute", form_data, function (res) {
                    if (res.data != null && res.data[0] != null) {
                        if (res.data[0].code == 200) {
                            if (res.data[0].type != "modify" && res.data[0].type != "other") {
                                $(".fw-sql-result .am-tabs li.result-data.am-active").data("sql", res.data[0].stmt);
                                $(".fw-sql-result .am-tabs li.result-data.am-active").data("total", res.data[0].total);
                                $(".fw-sql-result .am-tabs li.result-data.am-active").data("time", res.data[0].times);
                                $(".fw-sql-result .am-tabs div.result-data.am-active table tbody").remove();
                                $(".fw-sql-result .am-tabs div.result-data.am-active table").append($.dataTable.drawTbody(res.data[0].column, res.data[0].data));
                            }
                            if (typeof callback == "function") {
                                callback(res);
                            }
                        } else {
                            $.modal.alertError(res.data[0].msg);
                            return;
                        }
                    }
                }, function (res) {
                    $.dataTable.executeOne(sql_code, page);
                });
            },
            // 绘制表格
            drawTable: function (id, item) {
                $("#" + id).append($.dataTable.drawThead(item.column));
                $("#" + id).append($.dataTable.drawTbody(item.column, item.data));
            },
            // 回值表格头
            drawThead: function (columns) {
                var thead = `<thead>\r\n<tr onmousedown="mouseDown(event)" onmousemove="mouseMove(event)" onmouseup="mouseUp(event)"><th class="data-th0 sticky" width="15"></th>`;
                var dynamicHeader = [];
                for (var i = 0; i < columns.length; i++) {
                    var width_ = (columns[i].maxCharsCount * 9 + 14);
                    width_ = width_ > 185 ? 185 : width_;
                    thead += `<th class="data-th" width="` + width_ + `" data-tablename="` + (columns[i].tableName == undefined ? "" : columns[i].tableName) + `">` + columns[i].columnName + `</th>\r\n`;
                }
                thead += `<th class="data-th1"></th>\r\n`;
                thead += `</tr>\r\n</thead>`;
                return thead;
            },
            // 回值表格体
            drawTbody: function (columns, datas) {
                var tbody = `<tbody>`;
                for (var i = 0; i < datas.length; i++) {
                    if (i == 0) {
                        tbody += `<tr class="data-tr data-td-select" data-row="` + (i + 1) + `"><td class="data-td0 sticky"></td>`;
                    } else {
                        tbody += `<tr class="data-tr" data-row="` + (i + 1) + `"><td class="data-td0 sticky"></td>`;
                    }
                    for (var j = 0; j < columns.length; j++) {
                        if ((new Map(Object.entries(datas[i]))).get(columns[j].columnName) == null){
                            tbody +=
                                `<td class="data-td">` +
                                `<span class="am-hide">NULL</span>` +
                                `<div contenteditable="true" spellcheck="false" data-column="` + columns[j].columnName + `" data-numbercol="` + columns[j].isNumberColumn + `">NULL</div>` +
                                `</td>\r\n`;
                        } else if(columns[j].isNumberColumn == true && columns[j].columnType == -7 && columns[j].columnTypeName == 'bool') {
                            var bool_val;
                            if((new Map(Object.entries(datas[i]))).get(columns[j].columnName) == 't'){
                                bool_val = 'true';
                            }else if((new Map(Object.entries(datas[i]))).get(columns[j].columnName) == 'f'){
                                bool_val = 'false';
                            }else {
                                bool_val = (new Map(Object.entries(datas[i]))).get(columns[j].columnName);
                            }
                            tbody +=
                                `<td class="data-td">` +
                                `<span class="am-hide">` + bool_val + `</span>` +
                                `<div contenteditable="true" spellcheck="false" data-column="` + columns[j].columnName + `" data-numbercol="` + columns[j].isNumberColumn + `">` + bool_val + `</div>` +
                                `</td>\r\n`;
                        } else {
                            tbody +=
                                `<td class="data-td">` +
                                `<span class="am-hide">` + (new Map(Object.entries(datas[i]))).get(columns[j].columnName) + `</span>` +
                                `<div contenteditable="true" spellcheck="false" data-column="` + columns[j].columnName + `" data-numbercol="` + columns[j].isNumberColumn + `">` + (new Map(Object.entries(datas[i]))).get(columns[j].columnName) + `</div>` +
                                `</td>\r\n`;
                        }
                    }
                    tbody += `</tr>\r\n`;
                }
                return tbody;
            },
            // 刷新表格
            refresh: function () {
                $.dataTable.executeOne(
                    encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text())))),
                    $("#fw-footer-pagebtns input[name='page']").val(),
                    function () {
                        $.tableOperate.resetFooterBtns();
                    });
            },
            exportData: function () {
                var form_obj = $("#form-sql-search").serializeObject();
                form_obj["sqlCode"] = encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text()))));
                form_obj["total"] = $(".fw-sql-result .am-tabs li.result-data.am-active").data("total");
                try {
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', prefix + "/exportExcel", true);
                    xhr.responseType = 'blob';
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.onload = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            $.modal.msgSuccess("后台正在处理您的导出请求，稍后请留意文件的下载");
                            const data = xhr.response;
                            if (data.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                                const blob = new Blob([data]);
                                const blobUrl = window.URL.createObjectURL(blob);
                                const a = document.createElement('a');
                                a.style.display = 'none';
                                a.download = '当前查询（' + $(".result-data.am-active > a").text() + '）数据导出.xlsx';
                                a.href = blobUrl;
                                a.click();
                                window.URL.revokeObjectURL(a.href);
                            } else if (data.type == 'application/json' && data.size == 47) {
                                $.validate.openSafe(function (res) {
                                    $.dataTable.exportData();
                                });
                            } else {
                                $.modal.alertError("导出异常");
                            }
                        } else {
                            $.modal.alertError("导出异常");
                        }
                    };
                    xhr.onerror = function () {
                        $.modal.alertError("网络错误");
                    };
                    xhr.send(JSON.stringify(form_obj));
                } catch (e) {
                    $.modal.alertError("导出异常：" + e);
                }
            },
        },
        // 表格数据操作封装处理
        tableOperate: {
            // set 空字符串
            setEmptyString: function (opt, callback) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                $.each($table.find("tr.data-tr td.data-td-select"), function (index, item) {
                    $(item).find("div").text("");
                    $(item).removeClass("data-td-select").addClass("data-td-change");
                    $(item).parent(".data-tr").removeClass("data-tr-selects").removeClass("data-tr-select").removeClass("data-td-select").addClass("data-tr-change");
                });
                $.tableOperate.resetFooterBtns();
                $("#fw-footer-operbtn-commit, #fw-footer-operbtn-cancel").removeClass("fw-btn-disabled");
                if (typeof callback == "function") {
                    callback();
                }
            },
            // set Null
            setNull: function (opt, callback) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                $.each($table.find("tr.data-tr td.data-td-select"), function (index, item) {
                    $(item).find("div").text("NULL");
                    $(item).removeClass("data-td-select").addClass("data-td-change");
                    $(item).parent(".data-tr").removeClass("data-tr-selects").removeClass("data-tr-select").removeClass("data-td-select").addClass("data-tr-change");
                });
                $.tableOperate.resetFooterBtns();
                $("#fw-footer-operbtn-commit, #fw-footer-operbtn-cancel").removeClass("fw-btn-disabled");
                if (typeof callback == "function") {
                    callback();
                }
            },
            // 保存更改
            saveChanged: function (opt, callback) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                // 提交修改处理
                var tablename = $table.find("thead tr th.data-th").first().data("tablename");
                $table.find("thead tr th.data-th").each(function (index) {
                    if ($(this).data("tablename") !== tablename) {
                        tablename = "请在此处填写表名";
                        return false; // 一旦发现不同的值，立即停止迭代
                    }
                });
                if (tablename == "请在此处填写表名") {
                    return;
                }
                var insert_sqls = "";
                $.each($table.find("tr.data-tr-add"), function (index, item) {
                    var col_values = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if ($(item2).find("div").text() != "NULL" && $(item2).find("div").text() != "null") {
                            col_values = "true";
                            return false; // 一旦发现不同的值，立即停止迭代
                        }
                    });
                    if (col_values == "") {
                        $(item).remove();
                        $.tableOperate.resetFooterBtns();
                        return false;
                    }
                    var sql_cols = "";
                    var sql_vals = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            sql_cols += " \"" + $(item2).find("div").data("column") + "\",";
                            if ($(item2).find("div").data("numbercol") || $(item2).find("div").text() == "NULL") {
                                sql_vals += " " + $(item2).find("div").text() + ","
                            } else {
                                sql_vals += " '" + $(item2).find("div").text() + "',"
                            }
                        } else {
                            sql_cols += " \"" + $(item2).find("div").data("column") + "\"";
                            if ($(item2).find("div").data("numbercol") || $(item2).find("div").text() == "NULL") {
                                sql_vals += " " + $(item2).find("div").text()
                            } else {
                                sql_vals += " '" + $(item2).find("div").text() + "'"
                            }
                        }
                    });
                    if (sql_cols == "" || sql_vals == "") {
                        return true;
                    }
                    insert_sqls += "INSERT INTO \"" + tablename + "\" (" + sql_cols + ") VALUES (" + sql_vals + ");\r\n";
                });
                var update_sqls = "";
                $.each($table.find("tr.data-tr-change"), function (index, item) {
                    var sql_set = "";
                    $.each($(item).find(".data-td-change"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td-change").length - 1) {
                            if ($(item2).find("div").text() == "NULL" || $(item2).find("div").text() == "null") {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text() + ",";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text() + ",";
                            } else {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").text() + "',";
                            }
                        } else {
                            if ($(item2).find("div").text() == "NULL" || $(item2).find("div").text() == "null") {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text();
                            } else {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").text() + "'";
                            }
                        }
                    });
                    if (sql_set == "") {
                        return true;
                    }
                    var sql_where = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text() + " AND";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text() + " AND";
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "' AND";
                            }
                        } else {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text();
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "'";
                            }
                        }
                    });
                    update_sqls += "UPDATE \"" + tablename + "\" SET" + sql_set + " WHERE" + sql_where + ";\r\n";
                });
                if (insert_sqls != "") {
                    $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode(insert_sqls)))), null, function () {
                        $.dataTable.refresh();
                        if (typeof callback == "function") {
                            callback();
                        }
                    });
                }
                if (update_sqls != "") {
                    $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode(update_sqls)))), null, function () {
                        $.dataTable.refresh();
                        if (typeof callback == "function") {
                            callback();
                        }
                    });
                }
            },
            // 删除记录
            deleteRecord: function (opt, callback) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                var delete_sqls = "";
                var delete_rows = 0;
                var tablename = $table.find("thead tr th.data-th").first().data("tablename");
                $table.find("thead tr th.data-th").each(function (index) {
                    if ($(this).data("tablename") !== tablename) {
                        tablename = "请在此处填写表名";
                        return false; // 一旦发现不同的值，立即停止迭代
                    }
                });
                if (tablename == "请在此处填写表名") {
                    return;
                }
                $.each($table.find("tr.data-tr-select, tr.data-tr-selects, tr.data-td-select, tr.data-td-selects"), function (index, item) {
                    var sql_where = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text() + " AND";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text() + " AND";
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "' AND";
                            }
                        } else {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text();
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "'";
                            }
                        }
                    });
                    if (sql_where == "") {
                        return true;
                    }
                    delete_sqls += "DELETE FROM \"" + tablename + "\" WHERE" + sql_where + ";\r\n";
                    delete_rows += 1;
                });
                if (delete_sqls != "" && delete_rows > 0) {
                    // 异步执行删除操作
                    $.modal.confirm("确定要删除 " + delete_rows + " 条记录吗？", function () {
                        $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode(delete_sqls)))), null, function () {
                            $.dataTable.refresh();
                            if (typeof callback == "function") {
                                callback();
                            }
                        });
                    });
                }
            },
            // 复制为 Insert 语句
            copyToInsertSql: function (opt) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                var insert_sqls = "";
                var tablename = $table.find("thead tr th.data-th").first().data("tablename");
                $table.find("thead tr th.data-th").each(function (index) {
                    if ($(this).data("tablename") !== tablename) {
                        tablename = "请在此处填写表名";
                        return false; // 一旦发现不同的值，立即停止迭代
                    }
                });
                $.each($table.find("tr.data-tr-select, tr.data-tr-selects"), function (index, item) {
                    var sql_cols = "";
                    var sql_vals = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            sql_cols += " \"" + $(item2).find("div").data("column") + "\",";
                            if ($(item2).find("div").data("numbercol") || $(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_vals += " " + $(item2).find("div").prev("span").text() + ","
                            } else {
                                sql_vals += " '" + $(item2).find("div").prev("span").text() + "',"
                            }
                        } else {
                            sql_cols += " \"" + $(item2).find("div").data("column") + "\"";
                            if ($(item2).find("div").data("numbercol") || $(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_vals += " " + $(item2).find("div").prev("span").text()
                            } else {
                                sql_vals += " '" + $(item2).find("div").prev("span").text() + "'"
                            }
                        }
                    });
                    if (sql_cols == "" || sql_vals == "") {
                        return true;
                    }
                    insert_sqls += "INSERT INTO \"" + tablename + "\" (" + sql_cols + ") VALUES (" + sql_vals + ");\r\n";
                });
                $.each($table.find("tr.data-td-select, tr.data-td-selects"), function (index, item) {
                    var sql_cols = "";
                    var sql_vals = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            sql_cols += " \"" + $(item2).find("div").data("column") + "\",";
                            if ($(item2).find("div").data("numbercol") || $(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_vals += " " + $(item2).find("div").prev("span").text() + ","
                            } else {
                                sql_vals += " '" + $(item2).find("div").prev("span").text() + "',"
                            }
                        } else {
                            sql_cols += " \"" + $(item2).find("div").data("column") + "\"";
                            if ($(item2).find("div").data("numbercol") || $(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_vals += " " + $(item2).find("div").prev("span").text()
                            } else {
                                sql_vals += " '" + $(item2).find("div").prev("span").text() + "'"
                            }
                        }
                    });
                    if (sql_cols == "" || sql_vals == "") {
                        return true;
                    }
                    insert_sqls += "INSERT INTO \"" + tablename + "\" (" + sql_cols + ") VALUES (" + sql_vals + ");\r\n";
                });
                if (insert_sqls != "") {
                    $.common.copyToClipboard(insert_sqls);
                }
            },
            // 复制为 Update 语句
            copyToUpdateSql: function (opt) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                var update_sqls = "";
                var tablename = $table.find("thead tr th.data-th").first().data("tablename");
                $table.find("thead tr th.data-th").each(function (index) {
                    if ($(this).data("tablename") !== tablename) {
                        tablename = "请在此处填写表名";
                        return false; // 一旦发现不同的值，立即停止迭代
                    }
                });
                $.each($table.find("tr.data-tr-select, tr.data-tr-selects"), function (index, item) {
                    var sql_set = "";
                    var sql_where = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            if ($(item2).find("div").text() == "NULL" || $(item2).find("div").text() == "null") {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text() + ",";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text() + ",";
                            } else {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").text() + "',";
                            }
                        } else {
                            if ($(item2).find("div").text() == "NULL" || $(item2).find("div").text() == "null") {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text();
                            } else {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").text() + "'";
                            }
                        }
                        if (index2 != $(item).find(".data-td").length - 1) {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text() + " AND";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text() + " AND";
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "' AND";
                            }
                        } else {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text();
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "'";
                            }
                        }
                    });
                    if (sql_set == "" || sql_where == "") {
                        return true;
                    }
                    update_sqls += "UPDATE \"" + tablename + "\" SET" + sql_set + " WHERE" + sql_where + ";\r\n";
                });
                $.each($table.find("tr.data-td-select, tr.data-td-selects"), function (index, item) {
                    var sql_set = "";
                    $.each($(item).find(".data-td-select"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td-select").length - 1) {
                            if ($(item2).find("div").text() == "NULL" || $(item2).find("div").text() == "null") {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text() + ",";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text() + ",";
                            } else {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").text() + "',";
                            }
                        } else {
                            if ($(item2).find("div").text() == "NULL" || $(item2).find("div").text() == "null") {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").text();
                            } else {
                                sql_set += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").text() + "'";
                            }
                        }
                    });
                    if (sql_set == "") {
                        return true;
                    }
                    var sql_where = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text() + " AND";
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text() + " AND";
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "' AND";
                            }
                        } else {
                            if ($(item2).find("div").prev("span").text() == "NULL" || $(item2).find("div").prev("span").text() == "null") {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" is " + $(item2).find("div").prev("span").text();
                            } else if ($(item2).find("div").data("numbercol")) {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = " + $(item2).find("div").prev("span").text();
                            } else {
                                sql_where += " \"" + $(item2).find("div").data("column") + "\" = '" + $(item2).find("div").prev("span").text() + "'";
                            }
                        }
                    });
                    update_sqls += "UPDATE \"" + tablename + "\" SET" + sql_set + " WHERE" + sql_where + ";\r\n";
                });
                if (update_sqls != "") {
                    $.common.copyToClipboard(update_sqls);
                }
            },
            // 复制为 制表符分隔值（数据）
            copyToTableData: function (opt) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                var table_data = "";
                $.each($table.find("tr.data-tr-select, tr.data-tr-selects"), function (index, item) {
                    var row_data = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            row_data += $(item2).find("div").text() + "\t";
                        } else {
                            row_data += $(item2).find("div").text();
                        }
                    });
                    if (row_data == "") {
                        return true;
                    }
                    table_data += row_data + "\r\n";
                });
                $.each($table.find("tr.data-td-select, tr.data-td-selects"), function (index, item) {
                    var row_data = "";
                    $.each($(item).find(".data-td-select"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td-select").length - 1) {
                            row_data += $(item2).find("div").text() + "\t";
                        } else {
                            row_data += $(item2).find("div").text();
                        }
                    });
                    if (row_data == "") {
                        return true;
                    }
                    table_data += row_data + "\r\n";
                });
                if (table_data != "") {
                    $.common.copyToClipboard(table_data);
                }
            },
            // 复制为 制表符分隔值（字段名和数据）
            copyToTableColumnAndData: function (opt) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                var table_title_data = "";
                $.each($table.find("tr.data-tr-select, tr.data-tr-selects"), function (index, item) {
                    var row_title = "";
                    var row_data = "";
                    $.each($(item).find(".data-td"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td").length - 1) {
                            if (index == 0) {
                                row_title += $(item2).find("div").data("column") + "\t";
                            }
                            row_data += $(item2).find("div").text() + "\t";
                        } else {
                            if (index == 0) {
                                row_title += $(item2).find("div").data("column");
                            }
                            row_data += $(item2).find("div").text();
                        }
                    });
                    if ((index == 0 && row_title == "") || row_data == "") {
                        return true;
                    }
                    if (index == 0) {
                        table_title_data += row_title + "\r\n";
                    }
                    table_title_data += row_data + "\r\n";
                });
                $.each($table.find("tr.data-td-select, tr.data-td-selects"), function (index, item) {
                    var row_title = "";
                    var row_data = "";
                    $.each($(item).find(".data-td-select"), function (index2, item2) {
                        if (index2 != $(item).find(".data-td-select").length - 1) {
                            if (index == 0) {
                                row_title += $(item2).find("div").data("column") + "\t";
                            }
                            row_data += $(item2).find("div").text() + "\t";
                        } else {
                            if (index == 0) {
                                row_title += $(item2).find("div").data("column");
                            }
                            row_data += $(item2).find("div").text();
                        }
                    });
                    if ((index == 0 && row_title == "") || row_data == "") {
                        return true;
                    }
                    if (index == 0) {
                        table_title_data += row_title + "\r\n";
                    }
                    table_title_data += row_data + "\r\n";
                });
                if (table_title_data != "") {
                    $.common.copyToClipboard(table_title_data);
                }
            },
            // 清楚已框选的表格单元格
            clearTableSelection: function (opt) {
                var $table;
                if (opt.$trigger != undefined) {
                    $table = opt.$trigger.closest("table.result-data-table");
                } else {
                    $table = opt.closest("table.result-data-table");
                }
                $table.find('tr.data-tr').removeClass("data-tr-select").removeClass("data-tr-selects").removeClass("data-td-select").removeClass("data-td-selects");
                $table.find('tr.data-tr td.data-td').removeClass("data-td-select");
            },
            // 重置底部栏按钮组状态
            resetFooterBtns: function () {
                var tablename = $(".result-data.am-in").find("table thead tr th.data-th").first().data("tablename");
                $(".result-data.am-in").find("table thead tr th.data-th").each(function (index) {
                    if ($(this).data("tablename") !== tablename) {
                        tablename = "请在此处填写表名";
                        return false; // 一旦发现不同的值，立即停止迭代
                    }
                });
                $("#fw-footer-operbtn-add, #fw-footer-operbtn-delete, #fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-refresh, #fw-footer-operbtn-stop").removeClass("fw-btn-disabled");
                if (tablename == "请在此处填写表名") {
                    $("#fw-footer-operbtn-add, #fw-footer-operbtn-delete, #fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-stop").addClass("fw-btn-disabled");
                } else {
                    $("#fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-stop").addClass("fw-btn-disabled");
                }
            },
        }
    });
})(jQuery);


// --------------------------------------------------------------------------------------------------------------------


/**
 * 表格数据操作--事件监听
 */
$(function () {
    // 结果选项卡--点击调整底部操作栏
    $(".fw-sql-result").on('click', 'li.result-info', function (event) {
        event.stopPropagation();
        $("#fw-footer-operbtns").addClass("am-hide");
        $("#fw-footer-operinfo").addClass("am-hide");
        $("#fw-footer-opertime").addClass("am-hide");
        $("#fw-footer-pageinfo").addClass("am-hide");
        $("#fw-footer-pagebtns").addClass("am-hide");
        $("#fw-toolbar-export").addClass("am-hide");
    });
    $(".fw-sql-result").on('click', 'li.result-data', function (event) {
        event.stopPropagation();
        $("#fw-toolbar-export").removeClass("am-hide");

        var tablename = $("#result-data-" + $(this).index() + " .data-th").first().data("tablename");
        $("#result-data-" + $(this).index() + " .data-th").each(function (index) {
            if ($(this).data("tablename") !== tablename) {
                tablename = "请在此处填写表名";
                return false; // 一旦发现不同的值，立即停止迭代
            }
        });
        $("#fw-footer-operbtn-add, #fw-footer-operbtn-delete, #fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-refresh, #fw-footer-operbtn-stop").removeClass("fw-btn-disabled");
        if (tablename == "请在此处填写表名") {
            $("#fw-footer-operbtn-add, #fw-footer-operbtn-delete, #fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-stop").addClass("fw-btn-disabled");
            // 设置单元格禁止编辑
            $("#result-data-" + $(this).index() + " .data-td div").attr("contenteditable", false);
        } else {
            $("#fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-stop").addClass("fw-btn-disabled");
        }
        $("#fw-footer-operbtns").removeClass("am-hide");

        $("#fw-footer-operinfo").removeClass("am-hide");
        $("#fw-footer-operinfo").text($(this).data("sql"));
        $("#fw-footer-operinfo").attr("title", $(this).data("sql"));
        $("#fw-footer-opertime").removeClass("am-hide");
        $("#fw-footer-opertime").text("查询时间: " + $(this).data("time") + "s");

        var total = $(this).data("total");
        total = parseInt(total);
        if (total > 0) {
            $("#fw-footer-pageinfo").removeClass("am-hide");
            $("#fw-footer-pageinfo .data-row").text(1);
            var size = $("#form-sql-search input[name='size']").val();
            size = parseInt(size);
            $("#fw-footer-pageinfo .data-total").text((size > total ? total : size));
            $("#fw-footer-pageinfo .data-page").text($(this).data("page"));
            $("#fw-footer-pagebtns").removeClass("am-hide");
            $("#fw-footer-pagebtns input[name='page']").val(1);
            $("#page-step-forward input[name='total']").val(Math.ceil(total / size));
        }
    });

    /* 数据行--鼠标悬浮，动态改变底部栏显示行数 */
    $(".fw-sql-result").on('mouseenter', 'div.result-data.am-active.am-in table tr.data-tr', function (event) {
        $("#fw-footer-pageinfo .data-row").html($(this).data("row"));
    });

    /* 数据行、单元格--鼠标拖拽框选 */
    var isMouseDown = false;
    var startCell, endCell;
    var posL, posT;
    var intervalId1, intervalId2;
    var rowStart, rowEnd, colStart, colEnd;
    $(".fw-sql-result").on('mousedown', 'div.result-data.am-active.am-in table tr.data-tr td', function (event) {
        startCell = $(this);
        endCell = $(this);
        // posX = event.clientLeft;//鼠标点击时候的位置
        // posy = event.close_right;//鼠标点击时候的位置

        if (!startCell.parent("data-tr").hasClass("data-tr-add") && !startCell.parent("data-tr").hasClass("data-tr-change") &&
            startCell.parent("data-tr").siblings(".data-tr-add,.data-tr-change").length > 0) {
            $.tableOperate.saveChanged(startCell);
            return;
        }
        if (!startCell.hasClass("data-td0") && (startCell.find("div").hasClass("fw-focus") || startCell.find("div").is(":focus"))) {
            return;
        }
        if (!startCell.hasClass("data-td0") && event.which == 3) {
            return;
        }
        if (event.which == 3) {
            if (!startCell.parent(".data-tr").hasClass("data-tr-select") && !startCell.parent(".data-tr").hasClass("data-tr-selects")
                && !startCell.parent(".data-tr").hasClass("data-td-select") && !startCell.parent(".data-tr").hasClass("data-td-selects")) {
                $.tableOperate.clearTableSelection(startCell);
                startCell.parent(".data-tr").addClass("data-tr-select");
            }
            return;
        }
        event.preventDefault();
        isMouseDown = true;
        $.common.clearSelection();
        startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr td.data-td div').removeClass("fw-focus").blur();
        $.tableOperate.clearTableSelection(startCell);

    });
    $(document).on('mouseup', function (event) {
        // 如果不是排除的子元素，执行你的逻辑
        if (isMouseDown) {
            // 检查事件是否来源于排除的子元素
            if ($(event.target).closest('div.result-data.am-active.am-in table tr.data-tr td').length) {
                // 如果是排除的子元素，则不执行任何操作
                // 停止定时器
                clearInterval(intervalId1);
                clearInterval(intervalId2);
                return;
            }
            isMouseDown = false;
            // 停止定时器
            clearInterval(intervalId1);
            clearInterval(intervalId2);
        }
        $(document).off('mousemove');
    });
    $(document).on('mousemove', function (event) {
        // 停止定时器
        clearInterval(intervalId1);
        clearInterval(intervalId2);
        // 如果不是排除的子元素，执行你的逻辑
        if (isMouseDown && event.which != 3) {
            // 检查事件是否来源于排除的子元素
            if ($(event.target).closest('div.result-data.am-active.am-in table tr.data-tr td').length) {
                posL = null;
                posT = null;
                // 如果是排除的子元素，则不执行任何操作
                return;
            }
            var $tobdy = $("div.result-data.am-active.am-in");
            var x1 = $tobdy.offset().left;
            var x2 = $tobdy.width() + x1 - 15;
            posL = event.clientX - 16;
            var y1 = $tobdy.offset().top;
            var y2 = $tobdy.height() + y1 - 25;
            posT = event.clientY - 24;

            var vMoveTime = 500, hMoveTime = 500;
            if (posL < x1) {
                vMoveTime = 500 - (x1 - posL) * 10 < 0 ? 0 : 500 - (x1 - posL) * 10;
            } else if (posL > x2) {
                vMoveTime = 500 - (posL - x2) * 10 < 0 ? 0 : 500 - (posL - x2) * 10;
            }
            if (posT < y1) {
                hMoveTime = 500 - (y1 - posT) * 10 < 0 ? 0 : 500 - (y1 - posT) * 10;
            } else if (posT > y2) {
                hMoveTime = 500 - (posT - y2) * 10 < 0 ? 0 : 500 - (posT - y2) * 10;
            }
            // 设置定时器，每隔一定时间执行一次asyncOperation
            intervalId1 = setInterval(function () {
                if (startCell.hasClass("data-td0")) { // 行选
                    for (var i = rowStart; i <= rowEnd; i++) {
                        if (i == endCell.parent().index()) {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-tr-select');
                        } else {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-tr-selects');
                        }
                    }
                } else { //单元格选
                    for (var i = rowStart; i <= rowEnd; i++) {
                        if (i == endCell.parent().index()) {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-td-select');
                        } else {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-td-selects');
                        }
                        for (var j = colStart; j <= colEnd; j++) {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).find('td.data-td').eq(j - 1).addClass('data-td-select');
                        }
                    }
                }
                if (isMouseDown && posL < x1) {
                    if (colStart > 0) {
                        var colPrev = startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(rowStart).find('td.data-td').eq(colStart).prev();
                        $('div.result-data.am-active.am-in').scrollLeft(($('div.result-data.am-active.am-in').scrollLeft() - colPrev.width()));
                        colStart = colPrev.index() - 1;
                    } else {
                        clearInterval(intervalId1);
                    }
                } else if (isMouseDown && posL > x2) {
                    if (colEnd <= startCell.parent("tr.data-tr").find(".data-td").length) {
                        var colNext = startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(rowStart).find('td.data-td').eq(colEnd - 2).next();
                        if (colNext != undefined) {
                            $('div.result-data.am-active.am-in').scrollLeft(($('div.result-data.am-active.am-in').scrollLeft() + colNext.width()));
                            colEnd = colNext.index() + 1;
                        }
                    } else {
                        clearInterval(intervalId1);
                    }
                } else {
                    // 停止定时器
                    clearInterval(intervalId1);
                }
            }, vMoveTime); // 每1000毫秒执行一
            // 设置定时器，每隔一定时间执行一次asyncOperation
            intervalId2 = setInterval(function () {
                if (startCell.hasClass("data-td0")) { // 行选
                    for (var i = rowStart; i <= rowEnd; i++) {
                        if (i == endCell.parent().index()) {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-tr-select');
                        } else {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-tr-selects');
                        }
                    }
                } else { //单元格选
                    for (var i = rowStart; i <= rowEnd; i++) {
                        if (i == endCell.parent().index()) {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-td-select');
                        } else {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-td-selects');
                        }
                        for (var j = colStart; j <= colEnd; j++) {
                            startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).find('td.data-td').eq(j - 1).addClass('data-td-select');
                        }
                    }
                }
                if (isMouseDown && posT < y1) {
                    if (rowStart > 0) {
                        $('div.result-data.am-active.am-in').scrollTop(($('div.result-data.am-active.am-in').scrollTop() - 24));
                        rowStart -= 1;
                    } else {
                        clearInterval(intervalId2);
                    }
                } else if (isMouseDown && posT > y2) {
                    if (rowEnd <= startCell.parent().siblings().length) {
                        $('div.result-data.am-active.am-in').scrollTop(($('div.result-data.am-active.am-in').scrollTop() + 24));
                        rowEnd += 1;
                    } else {
                        clearInterval(intervalId2);
                    }
                } else {
                    // 停止定时器
                    clearInterval(intervalId2);
                }
            }, hMoveTime); // 每1000毫秒执行一
        }
    });
    $(".fw-sql-result").on('mousemove', 'div.result-data.am-active.am-in table tr.data-tr td', function (event) {
        endCell = $(this);
        if (isMouseDown && event.which != 3 && endCell != startCell) {
            // 停止定时器
            clearInterval(intervalId1);
            clearInterval(intervalId2);
            $.tableOperate.clearTableSelection(startCell);

            rowStart = Math.min(startCell.parent().index(), endCell.parent().index());
            rowEnd = Math.max(startCell.parent().index(), endCell.parent().index());

            if (startCell.hasClass("data-td0")) { // 行选
                for (var i = rowStart; i <= rowEnd; i++) {
                    if (i == endCell.parent().index()) {
                        startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-tr-select');
                    } else {
                        startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-tr-selects');
                    }
                }
            } else { //单元格选
                if (!endCell.hasClass("data-td0")) {
                    colStart = Math.min(startCell.index(), endCell.index());
                }
                colEnd = Math.max(startCell.index(), endCell.index());
                for (var i = rowStart; i <= rowEnd; i++) {
                    if (i == endCell.parent().index()) {
                        startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-td-select');
                    } else {
                        startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).addClass('data-td-selects');
                    }
                    for (var j = colStart; j <= colEnd; j++) {
                        startCell.parent("tr.data-tr").parent("tbody").find('tr.data-tr').eq(i).find('td.data-td').eq(j - 1).addClass('data-td-select');
                    }
                }

            }

        }
    });

    $(".fw-sql-result").on('mouseup', 'div.result-data.am-active.am-in table tr.data-tr td', function (event) {
        isMouseDown = false;
        if (startCell.hasClass("data-td0")) { // 行选
            if (!startCell.parent().hasClass("data-tr-select") && !startCell.parent().hasClass("data-tr-selects")) {
                $.tableOperate.clearTableSelection(startCell);
                startCell.parent().addClass("data-tr-select");
            }
        }
        $(".fw-sql-result").off('mousemove', 'table tr.data-tr td');
    });
    $(".fw-sql-result").on('contextmenu', 'div.result-data.am-active.am-in table tr.data-tr td.data-td', function (event) {
        $(this).parent("tr.data-tr").parent("tbody").find('tr.data-tr .data-td div').blur().removeClass("fw-focus");
        var lenght = $(this).parent("tr.data-tr").parent("tbody").find("tr.data-tr-select, tr.data-tr-selects, tr.data-td-selects").length;
        if (lenght > 0) {
            return;
        }
        if (!$(this).hasClass("data-td-add")) {
            $.tableOperate.clearTableSelection($(this));
        }
        $(this).addClass("data-td-select");
        if (!$(this).parent(".data-tr").hasClass("data-td-add")) {
            $(this).parent(".data-tr").addClass("data-td-select");
        }
    });

    $(".fw-sql-result").on('click', 'div.result-data.am-active.am-in table tr.data-tr td.data-td div', function (event) {
        event.stopPropagation();

        if (!$(this).parent(".data-td").parent(".data-tr").hasClass("data-tr-add") && !$(this).parent(".data-td").hasClass("data-td-change")) {
            $.tableOperate.clearTableSelection($(this));
            $(this).parent(".data-td").parent(".data-tr").addClass("data-td-select");
        }

        if (!$(this).hasClass("fw-focus")) {
            $(this).parent().siblings().find("div.fw-focus").removeClass("fw-focus");
            $(this).addClass("fw-focus");
            $.common.setCssScrollEnd(this);
            if (!$(this).parent(".data-td").parent(".data-tr").hasClass("data-tr-add") && !$(this).parent(".data-td").hasClass("data-td-change")
                && $(this).parent(".data-td").parent(".data-tr").siblings(".data-tr-add,.data-tr-change").length > 0) {
                if ($(this).parent(".data-td").parent(".data-tr").siblings(".data-tr-add").length > 0) {
                    var isSave = false;
                    $.each($(this).parent(".data-td").parent(".data-tr").siblings(".data-tr-add").find("td.data-td-add div"), function (index, item) {
                        if ($(item).text() != "NULL" && $(item).text() != "null") {
                            isSave = true;
                            return false;
                        }
                    });
                    if (!isSave) {
                        $(this).parent(".data-td").parent(".data-tr").siblings(".data-tr-add").remove();
                        $.tableOperate.resetFooterBtns();
                        return;
                    }
                }
                $.tableOperate.saveChanged($(this));
            }
        }
    });
    $(".fw-sql-result").on('dblclick', 'div.result-data.am-active.am-in table tr.data-tr td.data-td div', function (event) {
        event.stopPropagation();
        $.common.dbClickSelectText(this);
    });
    $(".fw-sql-result").on('keyup', 'div.result-data.am-active.am-in table tr.data-tr td.data-td div', function (event) {
        if ($(this).text() !== ($(this).prev("span").text() + "")) {
            if ($(this).parent(".data-td").hasClass("data-td-add") || $(this).parent(".data-td").parent(".data-tr").hasClass("data-tr-add")) {
                return;
            }
            $(this).parent(".data-td").removeClass("data-td-select").addClass("data-td-change");
            $(this).parent(".data-td").parent(".data-tr").removeClass("data-tr-selects").removeClass("data-tr-select").removeClass("data-td-select").addClass("data-tr-change");
            $("#fw-footer-operbtn-cancel, #fw-footer-operbtn-commit").removeClass("fw-btn-disabled");
        } else {
            $(this).parent(".data-td").removeClass("data-td-select").removeClass("data-td-change");
            $(this).parent(".data-td").parent(".data-tr").removeClass("data-tr-selects").removeClass("data-tr-select").removeClass("data-td-select").removeClass("data-tr-change");
            $("#fw-footer-operbtn-cancel, #fw-footer-operbtn-commit").addClass("fw-btn-disabled");
        }
    });
    $(".fw-sql-result").on('paste', "div.result-data.am-active.am-in table tr.data-tr td.data-td div", function (e) {
        e.stopPropagation();
        e.preventDefault();
        var text = '', event = (e.originalEvent || e);
        if (event.clipboardData && event.clipboardData.getData) {
            text = event.clipboardData.getData('text/plain');
        } else if (window.clipboardData && window.clipboardData.getData) {
            text = window.clipboardData.getData('Text');
        }
        //去除文本头尾的空白符
        // text = text.trim();
        if (document.queryCommandSupported('insertText')) {
            document.execCommand('insertText', false, text);
        } else {
            document.execCommand('paste', false, text);
        }
    });

    /* 表格右键菜单 */
    $.contextMenu({
        selector: ".fw-sql-result div.result-data.am-active.am-in table tr.data-tr td",
        trigger: 'right',
        autoHide: true,
        items: {
            "setEmptyString": {
                name: "设置为空白字符串",
                callback: function (key, opt) {
                    $.tableOperate.setEmptyString(opt);
                }
            },
            "setNull": {
                name: "设置为 NULL",
                callback: function (key, opt) {
                    $.tableOperate.setNull(opt);
                }
            },
            "step1": "---------",
            "deleteRecord": {
                name: "删除记录",
                callback: function (key, opt) {
                    $.tableOperate.deleteRecord(opt);
                }
            },
            "step2": "---------",
            "copy": {
                name: "复制",
                callback: function (key, opt) {
                    $.tableOperate.copyToTableData(opt);
                }
            },
            "copyTo": {
                name: "复制为",
                items: {
                    "copyToInsertSql": {
                        name: "Insert 语句",
                        callback: function (key, opt) {
                            $.tableOperate.copyToInsertSql(opt);
                        }
                    },
                    "copyToUpdateSql": {
                        name: "Update 语句",
                        callback: function (key, opt) {
                            $.tableOperate.copyToUpdateSql(opt);
                        }
                    },
                    "step1": "---------",
                    "copyToTableData": {
                        name: "制表符分隔值（数据）",
                        callback: function (key, opt) {
                            $.tableOperate.copyToTableData(opt);
                        }
                    },
                    "copyToTableColumnAndData": {
                        name: "制表符分隔值（字段名和数据）",
                        callback: function (key, opt) {
                            $.tableOperate.copyToTableColumnAndData(opt);
                        }
                    }
                }
            }
        }
    });

});

/**
 * 功能按钮操作--事件监听
 */
$(function () {
    // 底部栏--操作按钮组--信息查看 */
    $(".footer-infoview").click(function () {
        jianshezhong();
    });
    // 底部栏--操作按钮组--新增 */
    $("#fw-footer-operbtn-add").click(function () {
        var $table = $(".result-data.am-active table.result-data-table");
        if ($table.find("tr.data-tr-change td.data-td-change").length > 0) {
            $.tableOperate.saveChanged($table);
        }
        $.tableOperate.clearTableSelection($table);
        // 设置按钮状态
        $("#fw-footer-operbtn-add, #fw-footer-operbtn-delete, #fw-footer-operbtn-commit, #fw-footer-operbtn-cancel, #fw-footer-operbtn-refresh, #fw-footer-operbtn-stop").removeClass("fw-btn-disabled");
        $("#fw-footer-operbtn-add, #fw-footer-operbtn-delete, #fw-footer-operbtn-refresh, #fw-footer-operbtn-stop").addClass("fw-btn-disabled");
        // 新增空行
        var $tr = $table.find("tbody tr").last();
        var addRow = `<tr class="data-tr data-tr-add" data-row="` + ($tr.data("row") + 1) + `"><td class="data-td0 sticky"></td>`;
        $.each($tr.find("td.data-td"), function (index, item) {
            addRow += `<td class="data-td data-td-add"><div contenteditable="true" spellcheck="false" data-column="` + $(item).find("div").data("column") + `" data-numbercol="` + $(item).find("div").data("numbercol") + `" data-value="NULL" >NULL</div></td>\r\n`;
        });
        addRow += `</tr>\r\n`;
        $table.find("tbody").append(addRow);

        // 滚动的最后一行
        var lastRow = $table.find('tbody tr:last');
        $('.result-data').animate({
            scrollTop: lastRow.offset().top
        }, 1);

        $(this).blur();

    });
    // 底部栏--操作按钮组--删除 */
    $("#fw-footer-operbtn-delete").click(function () {
        var $table = $(".result-data.am-active table.result-data-table");
        if ($table.find("tr.data-tr-selects,tr.data-tr-select,tr.data-td-select,tr.data-tr-change,tr.data-tr-add").length > 0) {
            $.tableOperate.deleteRecord($table);
        }
        $(this).blur();
    });
    // 底部栏--操作按钮组--提交 */
    $("#fw-footer-operbtn-commit").click(function () {
        var $table = $(".result-data.am-active table.result-data-table");
        if ($table.find("tr.data-tr-selects,tr.data-tr-select,tr.data-td-select,tr.data-tr-change,tr.data-tr-add").length > 0) {
            if ($table.find("tr.data-tr-add").length > 0) {
                var isSave = false;
                $.each($table.find("tr.data-tr-add td.data-td-add div"), function (index, item) {
                    if ($(item).text() != "NULL" && $(item).text() != "null") {
                        isSave = true;
                        return false;
                    }
                });
                if (!isSave) {
                    $.modal.alertWarning("无效数据行！")
                    return;
                }
            }
            $.tableOperate.saveChanged($table);
        }
        $(this).blur();
    });
    // 底部栏--操作按钮组--取消 */
    $("#fw-footer-operbtn-cancel").click(function () {
        $.dataTable.refresh();
        $(this).blur();
    });
    // 底部栏--操作按钮组--刷新 */
    $("#fw-footer-operbtn-refresh").click(function () {
        $.dataTable.refresh();
        $(this).blur();
    });
    // 底部栏--操作按钮组--停止 */
    $("#fw-footer-operbtn-stop").click(function () {
        jianshezhong(); // 异步停止后台sql执行
        $(this).blur();
    });

    // 底部栏--分页按钮组--第一页 */
    $("#page-step-backward").click(function () {
        var cpage = $("#fw-footer-pagebtns input[name='page']").val();
        if (cpage != 1) {
            $("#fw-footer-pageinfo .data-page").text(1);
            $("#fw-footer-pagebtns input[name='page']").val(1);
            $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text())))), 1);
        }
        $(this).blur();
    });
    // 底部栏--分页按钮组--上一页 */
    $("#page-chevron-left").click(function () {
        var page = $("#fw-footer-pagebtns input[name='page']").val();
        if (page != 1) {
            page = parseInt(page) - 1;
            $("#fw-footer-pageinfo .data-page").text(page);
            $("#fw-footer-pagebtns input[name='page']").val(page);
            $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text())))), page);
        }
        $(this).blur();
    });
    // 底部栏--分页按钮组--下一页 */
    $("#page-chevron-right").click(function () {
        var page = $("#fw-footer-pagebtns input[name='page']").val();
        page = parseInt(page) + 1;
        $("#fw-footer-pageinfo .data-page").text(page);
        $("#fw-footer-pagebtns input[name='page']").val(page);
        $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text())))), page);
        $(this).blur();
    });
    // 底部栏--分页按钮组--最后一页 */
    $("#page-step-forward").click(function () {
        var page = $(this).find("input[name='total']").val();
        var cpage = $("#fw-footer-pagebtns input[name='page']").val();
        if (page != cpage) {
            $("#fw-footer-pageinfo .data-page").text(page);
            $("#fw-footer-pagebtns input[name='page']").val(page);
            $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text())))), page);
        }
        $(this).blur();
    });
    // 底部栏--分页按钮组--自定义页码跳转 */
    $("#fw-footer-pagebtns input[name='page']").keyup(function (event) {
        if (event.keyCode === 13) {
            var page = $("#fw-footer-pagebtns input[name='page']").val();
            $("#fw-footer-pageinfo .data-page").text(page);
            $("#fw-footer-pagebtns input[name='page']").val(page);
            $.dataTable.executeOne(encodeURIComponent($.base64.encode($.base64.encode($.base64.encode($("#fw-footer-operinfo").text())))), page);
            $(this).blur();
        }
    });

});


// --------------------------------------------------------------------------------------------------------------------

function mouseDown(e) {
    this.localTd = null;
    // 记录单元格
    if (!(e && e.target)) return;
    if ($(e.target).hasClass("data-th0") || $(e.target).hasClass("data-th1")) return;
    this.localTd = e.target;
    if (e.offsetX > this.localTd.offsetWidth - 10) {
        this.localTd.mouseDown = true;
        this.localTd.oldX = e.x;
        this.localTd.oldWidth = this.localTd.offsetWidth;
    }
}


/** 鼠标移动 */
function mouseMove(e) {
    if (!(e && e.target)) return;
    if (($(e.target).hasClass("data-th0")) ||
        ($(e.target).hasClass("data-th1") && (this.localTd == undefined || $(this.localTd).hasClass("data-th1")))) return;
    const vm = e.target;
    // 更改鼠标样式
    if (e.offsetX > vm.offsetWidth - 10) {
        vm.style.cursor = "col-resize";
    } else {
        vm.style.cursor = "default";
    }
    // 取出暂存的Table Cell
    // if (!this.localTd) this.localTd = vm;
    if (!this.localTd) return;
    if (this.localTd.mouseDown !== null && this.localTd.mouseDown === true) {
        this.localTd.style.cursor = "default";
        if (this.localTd.oldWidth + (e.x - this.localTd.oldX) > 0) {
            this.localTd.width =
                this.localTd.oldWidth + (e.x - this.localTd.oldX);
        }
        // 调整列宽
        this.localTd.style.width = this.localTd.width;
        this.localTd.style.cursor = "col-resize";
        // 调整该列中的每个Cell
        let table = this.localTd;
        while (table.tagName !== "TABLE") table = table.parentElement;
        for (let j = 0; j < table.rows.length; j++) {
            table.rows[j].cells[
                this.localTd.cellIndex
                ].width = this.localTd.width;
        }
    }
}

/** 鼠标抬起 */
function mouseUp(e) {
    // 结束宽度调整
    if (!(e && e.target)) return;
    if (!this.localTd) this.localTd = e.target;
    this.localTd.mouseDown = false;
    this.localTd.style.cursor = "default";
    this.localTd = undefined;
}
